import { FC, useMemo, useState } from 'react';
import Preview from './Preview';

import { ImgViewProps, PreviewProps } from './interface';
import { toArray } from '../_common/util';

import './style/index.less';
import FullScreenPreview from '@/biz-components/img-view/FullScreenPreview';
import ImgViewContext from '@/biz-components/img-view/context';
import useIndexes from '@/biz-components/hooks/useIndexes';

import { EyeOutlined } from '@ant-design/icons';

const ImgView: FC<ImgViewProps> = ({ images, width, height }) => {
  const { imgArray, lastIndex } = useMemo(() => {
    const imgArray = toArray(images) as PreviewProps['images'];

    const { length } = imgArray;
    const lastIndex = length - 1;

    return {
      imgArray,
      lastIndex,
    };
  }, [images]);

  const [currentIndex, prevFn, nextFn] = useIndexes(0, lastIndex);
  const [visible, setVisible] = useState(false);

  const handleClose = () => {
    setVisible(false);
  };

  const extraTools = useMemo(() => {
    return [
      {
        icon: <EyeOutlined />,
        onClick: () => {
          setVisible(true);
        },
      },
    ];
  }, []);

  return (
    <ImgViewContext.Provider
      value={{
        currentIndex,
        nextFn,
        prevFn,
      }}
    >
      <div
        className={'image'}
        style={{
          width,
          height,
        }}
      >
        <Preview images={imgArray} extraTools={extraTools} />
      </div>

      <FullScreenPreview images={imgArray} visible={visible} onClose={handleClose} />
    </ImgViewContext.Provider>
  );
};

export default ImgView;
